package com.jt.blog.interceptor;

import com.jt.blog.model.User;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;

/**
 * Created by Tim on 2016/8/27.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private final static String URL_ENCODER_CODE = "UTF-8";

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        HttpSession session = httpServletRequest.getSession();
        User user =(User)session.getAttribute("user");
        if(user == null){
            httpServletResponse.sendRedirect("/back/login?target="+ URLEncoder.encode(uri, URL_ENCODER_CODE));
        }
    }
}
